package controllers

import (
	"cinema/models"

	"github.com/astaxie/beego/context"

	"github.com/astaxie/beego"
)

type LoginController struct {
	beego.Controller
}

//退出
func (this *LoginController) Get() {
	isExit := this.Input().Get("exit") == "true"
	if isExit {
		this.Ctx.SetCookie("uname", "", -1, "/")
		this.Ctx.SetCookie("pwd", "", -1, "/")
		this.Redirect("", 302)
		return
	}
	this.TplName = "login.html"
}

//登录
//需要2个参数：
//name：用户名
//pwd：密码
func (this *LoginController) Post() {
	name := this.Input().Get("name")
	pwd := this.Input().Get("pwd")
	status, _ := models.Login(name, pwd)

	cookieAge := 0

	if status == 0 {
		cookieAge = 1<<31 - 1
		this.Ctx.SetCookie("name", name, cookieAge, "/")
		this.Ctx.SetCookie("pwd", pwd, cookieAge, "/")
		codejson := Message{0, nil, "登录成功"}
		//生成接口
		this.Data["json"] = codejson
		this.ServeJSON()
		this.Redirect("", 302)
		return
	} else {
		var codejson interface{}
		switch status {
		//返回的code  正确为0  错误为1
		case 1:
			codejson = Message{1, nil, "密码错误"}
		case 2:
			codejson = Message{1, nil, "不存在该用户"}
		case 3:
			codejson = Message{1, nil, "发生错误"}
		}
		this.Data["json"] = codejson
		this.ServeJSON()
		// this.Redirect("", 302)
		return
	}
}

func checkAccount(ctx *context.Context) (string, string, bool) {
	// name := ctx.GetCookie("name")
	// if name == "" {
	// 	return "", "", false
	// }
	// pwd := ctx.GetCookie("pwd")
	// if pwd == "" {
	// 	return "", "", false
	// }
	name := "shaofong"
	pwd := "12345678"
	status, _ := models.Login(name, pwd)
	if status != 0 {
		return "", "", false
	}
	return name, pwd, true
}
